'''
pip install paddlepaddle
pip install paddleocr
'''
import psutil
from paddleocr import PaddleOCR
from utils.uitils_logger import Mylogger
from utils.utils_config import CommonConfig, read_config_value

logger = Mylogger("service_ocr.log").get_logger()

# 初始化PaddleOCR，可以根据需要设置参数，如使用gpu、调整语言等
ocr = PaddleOCR(use_angle_cls=True, lang="ch")

count = 0

def baidu_predict(filePath):
    result = ocr.ocr(filePath, cls=True)
    words_result = []
    for line in result:
        for word_info in line:
            word = word_info[1][0]  # 文字内容
            confidence = word_info[1][1]  # 置信度
            position = word_info[0]  # 文字位置，四个点的坐标
            # 计算中心点坐标
            x_center = sum([point[0] for point in position]) / 4
            y_center = sum([point[1] for point in position]) / 4
            words_result.append({
                'words': word,
                'confidence': confidence,
                #'position': position,
                'x_center': x_center,
                'y_center': y_center
            })
    resp = {"words_result": words_result}
    global count
    count += 1
    logger.info(f"✅ 请求次数: {count} 请求成功:{len(words_result)}")
    return resp

def check_cpu_usage():
    # 获取当前 CPU 使用率，interval=1 表示等待1秒后计算平均使用率
    cpu_usage = psutil.cpu_percent(interval=1)

    threshold = int(read_config_value(CommonConfig.COMMON_CONFIG.value, CommonConfig.CPU_USAGE.value, "95"))

    if cpu_usage >= threshold:
        logger.error(f"❌ 当前 CPU 使用率: {cpu_usage}%   警告：CPU 使用率已达到或超过 {threshold}%！")
        return True
    else:
        logger.info(f"✅ 当前 CPU 使用率: {cpu_usage}%   CPU 使用率正常。")
        return False


